import { createSlice } from "@reduxjs/toolkit";
import request from "@/utils/request";
import { getToken, setToken as _setToken, removeToken } from "@/utils/index";

const userMsg = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {},
  },
  reducers: {
    setToken(state, { payload }) {
      _setToken(payload.data.token);
    },
    setUserInfo(state, { payload }) {
      state.userInfo = payload;
    },
    clearInfo(state) {
      state.token = "";
      state.userInfo = {};
      removeToken();
    },
  },
});
const { setToken, setUserInfo, clearInfo } = userMsg.actions;
function getUserMsg(data) {
  return async (dispatch) => {
    let res = await request.post("/authorizations", data);
    dispatch(setToken(res));
  };
}
function setUserMsg() {
  return async (dispatch) => {
    let res = await request.get("/user/profile");

    dispatch(setUserInfo(res.data));
  };
}
const reduce = userMsg.reducer;
export { getUserMsg, setUserMsg, clearInfo };

export default reduce;
